﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using System.Text.RegularExpressions;
using NetworkAssetManager.DataAccess;
using NetworkAssetManager.Entity;
using NetworkAssetManager.General;

namespace NetworkAssetManager.Forms
{
    public partial class FrmReport : Form
    {
        public FrmReport()
        {
            InitializeComponent();
        }

        private void btnGenerate_Click(object sender, EventArgs e)
        {

        }

        private void FrmReport_Load(object sender, EventArgs e)
        {
            LoadEntities();
            LoadMachines(); 
        }
        private void LoadMachines()
        {
            List<EntDiscover> discMachineList = null;
            discMachineList = Controller.Instance.GetMachineList();
            TreeNode node = lstMachines.Nodes.Add("All Machines");


            foreach (EntDiscover discover in discMachineList)
            {
                EntScan scan = Controller.Instance.GetLatestScan(discover.MachineID);

                if ( scan!= null)
                {
                    TreeNode temp = new TreeNode();
                    temp.Text = discover.MachineName;
                    temp.Tag = discover.MachineID.ToString() + "|" + scan.ScanID.ToString();
                    node.Nodes.Add(temp);
                    temp = null; 
                }
            }
        }
        private void LoadEntities()
        {
            Assembly asm = Assembly.GetExecutingAssembly();
            List<Type> namespaceList = new List<Type>();
            foreach (Type type in asm.GetTypes())
            {
                if (type.Namespace == "NetworkAssetManager.Entity")
                    namespaceList.Add(type);
            }
            foreach (Type entityType in namespaceList)
            {
                FillList(entityType);
            }
        }
        private void FillList(Type entityType)
        {
            string _entityName = entityType.Name;

            if ( /*_entityName == "EntProcesses" || */_entityName == "EntCredential" || /*
                _entityName == "EntServices" 
                                ||*/
                 _entityName == "EntDiscover" || _entityName == "EntScan" || _entityName == "IEntity")
            {
                return; 
            }
            string _trunName = _entityName.Remove(0, 3); 
            TreeNode node = lstEntity.Nodes.Add(_trunName);
            PropertyInfo[] pi = entityType.GetProperties();
            foreach (PropertyInfo prop in pi)
            {
                if (prop.Name == "ScanID" || prop.Name == "ClassName" || prop.Name == "Icon" || prop.Name == "NodeName")
                    continue;

                node.Nodes.Add(SplitCamelCase(prop.Name));
            }
        }
        private string SplitCamelCase(string inputCamelCaseString)
        {
            string sTemp = Regex.Replace(inputCamelCaseString, "([A-Z][a-z])", " $1", RegexOptions.Compiled).Trim();
            return Regex.Replace(sTemp, "([A-Z][A-Z])", " $1", RegexOptions.Compiled).Trim();
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            FrmSheet objFrmSheet = new FrmSheet();
            objFrmSheet.ResultDataSet = GenerateDataSet();
            objFrmSheet.ShowDialog(); 

        }

        private DataSet GenerateDataSet()
        {
            string query = string.Empty;
            string machineIDFilter = string.Empty;
            string scanIDFilter = string.Empty; 
            char[] sep = { '|' };
            EntityDb entityDb = new EntityDb();
            DataSet dsResults = new DataSet("Results");

            foreach (TreeNode nodeMachines in lstMachines.Nodes)
            {
                if (lstMachines.GetChecked(nodeMachines) == TriStateTreeView.CheckState.Checked ||
                    lstMachines.GetChecked(nodeMachines) == TriStateTreeView.CheckState.GreyChecked)
                {

                    foreach (TreeNode mach in nodeMachines.Nodes)
                    {

                        if (lstEntity.GetChecked(mach) == TriStateTreeView.CheckState.Checked)
                        {
                            string tagtext = (string)mach.Tag;
                            string[] values = tagtext.Split(sep); 

                            machineIDFilter = machineIDFilter + values[0] + ",";
                            scanIDFilter = scanIDFilter + values[1] + ",";
                        }
                    }
                }

            }
            machineIDFilter = machineIDFilter.TrimEnd(',', ' ');
            scanIDFilter = scanIDFilter.TrimEnd(',', ' ');



            query = @"SELECT MachineName, MAX(ScanID) AS ScanID
                                FROM (SELECT Discover.MachineName, Scan.ScanID
                                FROM Discover INNER JOIN Scan ON 
                                Discover.MachineID = Scan.MachineID
                                WHERE (Discover.MachineID IN (" + machineIDFilter+ "))) AS derivedtbl_1 GROUP BY MachineName";
            

            //SqlCeDataAdapter dataAdapter = new SqlCeDataAdapter(query, _connection);
            DataTable dtMachine = new DataTable();
            entityDb.RunQueryTable(query, ref dtMachine);

            if ( dtMachine.Rows.Count> 0)
            {
                dtMachine.TableName = "Machines";
                dsResults.Tables.Add(dtMachine);

                foreach (TreeNode node in lstEntity.Nodes)
                {
                    if (lstEntity.GetChecked(node) ==
                           TriStateTreeView.CheckState.Checked || lstEntity.GetChecked(node) ==
                           TriStateTreeView.CheckState.GreyChecked)
                    {
                        DataTable dtResult = new DataTable();
                        string temp = string.Empty;

                        StringBuilder sb = new StringBuilder();




                        sb.AppendFormat("SELECT ScanID, ");
                        foreach (TreeNode items in node.Nodes)
                        {
                            if (lstEntity.GetChecked(items) == TriStateTreeView.CheckState.Checked ||
                                lstEntity.GetChecked(items) == TriStateTreeView.CheckState.GreyChecked)
                            {
                                temp = items.Text;
                                temp = temp.Replace(" ", "");
                                sb.AppendFormat("{0}, ", temp);
                            }
                        }
                        sb.Remove(sb.Length - 2, 1);
                        sb.AppendFormat("FROM [{0}] where ScanID in ({1})", node.Text, scanIDFilter);

                        entityDb.RunQueryTable(sb.ToString(), ref dtResult);
                        dtResult.TableName = node.Text;
                        dsResults.Tables.Add(dtResult);

                        string tmpRelationName = "FK_SCAN_" + node.Text;
                        DataRelation relation1 = new DataRelation(
                            tmpRelationName,
                            dtMachine.Columns["ScanID"],
                            dtResult.Columns["ScanID"]);

                        dsResults.Relations.Add(relation1);
                        relation1.Nested = true;
                    }
                }
            }
            return dsResults;

        }


    }
}
